﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FarseerGames.FarseerPhysics.Dynamics.Springs;

namespace GraphicalSVN.WPFApp
{
    public class FixedLinearSpringVisualHelper
    {
        private readonly ILinearSpringVisual visual;
        private readonly FixedLinearSpring spring;
        private readonly LinearSpring linearSpring;
        public FixedLinearSpringVisualHelper(ILinearSpringVisual visual, FixedLinearSpring spring)
        {
            this.visual = visual;
            this.spring = spring;

            spring.SpringUpdated += OnSpringUpdated;
            Update();
        }

        public FixedLinearSpringVisualHelper(ILinearSpringVisual visual, LinearSpring spring)
        {
            this.visual = visual;
            this.linearSpring = spring;

            spring.SpringUpdated += OnLinearSpringUpdated;
            UpdateSpring();
        }

        bool OnSpringUpdated(Spring sender, FarseerGames.FarseerPhysics.Dynamics.Body body)
        {
            Update();
            return true;
        }

        bool OnLinearSpringUpdated(Spring sender, FarseerGames.FarseerPhysics.Dynamics.Body body1, FarseerGames.FarseerPhysics.Dynamics.Body body2)
        {
            UpdateSpring();
            return true;
        }


        private void UpdateSpring()
        {
            if (linearSpring == null) return;
            visual.Endpoint1 = linearSpring.Body1.GetWorldPosition(linearSpring.AttachPoint1);
            visual.Endpoint2 = linearSpring.Body2.GetWorldPosition(linearSpring.AttachPoint2);
        }

        private void Update()
        {
            if (spring == null) return;
            visual.Endpoint1 = spring.Body.GetWorldPosition(spring.BodyAttachPoint);
            visual.Endpoint2 = spring.WorldAttachPoint;
        }
    }
}
